package com.wanxs.mall.auth.controller;


import com.alibaba.fastjson.JSON;
import com.wanxs.mall.auth.feign.MemberFeginService;
import com.wanxs.mall.auth.feign.ThirdPartFeignService;
import com.wanxs.mall.auth.vo.LoginVo;
import com.wanxs.mall.auth.vo.UserRegisterVo;
import com.wanxs.mall.common.constant.AuthConstant;
import com.wanxs.mall.common.constant.SMSConstant;
import com.wanxs.mall.common.exception.BizCodeEnume;
import com.wanxs.mall.common.utils.Result;
import com.wanxs.mall.common.vo.MemberVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

//    @GetMapping("login.html")
//    public String login(){
//        return "index";
//    }
//    @GetMapping("reg.html")
//    public String reg(){
//        return "reg";
//    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeginService memberFeginService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public Result sendSmsCode(@RequestParam("phone") String phone){


        Object obj_redis_auth = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);

        if(obj_redis_auth != null && StringUtils.isNotEmpty(obj_redis_auth.toString())){
            String redis_auth = obj_redis_auth.toString();
            String[] auth_values = redis_auth.split("_");
            Long last_time = Long.valueOf(auth_values[1]);
            if(System.currentTimeMillis() - last_time <= 60000){
                return new Result().error(BizCodeEnume.VALID_SMS_EXCEPTION.getCode(),BizCodeEnume.VALID_SMS_EXCEPTION.getMsg());
            }
        }
        // 生成随机的验证码
        String code = new Random().nextInt(99999) + "";
        thirdPartFeignService.sendSmsCode(phone,code);
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX + phone ,code + "_" + System.currentTimeMillis() , 10 , TimeUnit.MINUTES);

        return new Result();
    }

    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        Map<String,String> map = new HashMap<>();
        if(result.hasErrors()){
            // 表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/reg";
        }else{
            // 验证码是否正确
            String code = (String)redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            code = code.split("_")[0];
            if(!code.equals(vo.getCode())){
                // 说明验证码不正确
                map.put("code","验证码错误");
                model.addAttribute("error",map);
                return "/reg";
            }else{
                // 验证码正确  删除验证码
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                // 远程调用对应的服务 完成注册功能
                Result r = memberFeginService.register(vo);
                if(r.getCode() == 0){
                    // 注册成功
                    return "redirect:http://msb.auth.com/login.html";
                }else{
                    // 注册失败
                    map.put("msg",r.getCode()+":" + r.getMsg());
                    model.addAttribute("error",map);
                    return "/reg";
                }
            }
        }

    }
    /**
     * 注册的方法
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo , HttpSession session, RedirectAttributes redirectAttributes){
        Result r = memberFeginService.login(loginVo);
        if(r.getCode() == 0){
            String entityJson = (String) r.getData();
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            // 表示登录成功
            return "redirect:http://mall.wanxs.com/home";
        }

        redirectAttributes.addAttribute("errors",r.getMsg());

        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.wanxs.com/login.html";


    }
}
